package com.dayuan.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.dayuan.bean.BackUser;
import com.dayuan.bean.Order;
import com.dayuan.bean.OrderInfo;
import com.dayuan.bean.UserInfo;
import com.dayuan.service.BackOrderService;
import com.dayuan.service.GoodsService;
import com.dayuan.service.UserInfoService;
import com.dayuan.utils.PatternUtils;
import com.dayuan.utils.SecurityUtil;
import com.dayuan.utils.ExportExcelUtils;
import com.dayuan.utils.pageHelper;
import com.dayuan.vo.BackOrderInfoVo;
import com.dayuan.vo.BackOrderVo;

@Controller
@RequestMapping("/backOrder")
public class BackOrderController {
	private static Logger logger = LoggerFactory.getLogger(BackOrderController.class);

	@Resource
	private BackOrderService backOrderService;
	@Resource
	private UserInfoService userInfoService;
	@Resource
	private GoodsService goodsService;

	/**
	 * 后台管理员获取订单主页内容
	 * 
	 * @param mid
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/adminGetOrders.shtml", method = { RequestMethod.GET, RequestMethod.POST })

	public ModelAndView adminGetOrders(Integer pageIndex, BackOrderVo backOrderVo, ModelMap modelMap) {

		try {
			getOrders(pageIndex,backOrderVo,modelMap);
			ModelAndView modelAndView = new ModelAndView("adminOrders", modelMap);
			return modelAndView;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("后台订单获取失败：" + e.getMessage());
		}
		return null;
	}

	/**
	 * 后台商家获取订单主页内容
	 * 
	 * @param mid
	 * @param modelMap
	 * @return
	 */

	@RequestMapping(value = "/userGetOrders.shtml", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView userGetOrders(Integer pageIndex, BackOrderVo backOrderVo, ModelMap modelMap) {
		try {
			backOrderVo.setMid(SecurityUtil.getBackUser().getId());
			getOrders(pageIndex,backOrderVo,modelMap);
			ModelAndView modelAndView = new ModelAndView("userOrders", modelMap);
			return modelAndView;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("后台订单获取失败：" + e.getMessage());
		}
		return null;
	}

	/**
	 * 获取订单页面的方法
	 * 
	 * @param pageIndex
	 * @param backOrderVo
	 * @param modelMap
	 * @return
	 */

	public ModelMap getOrders(Integer pageIndex, BackOrderVo backOrderVo, ModelMap modelMap) {

		if (pageIndex == null) {
			pageIndex = 1;
		}
		if (backOrderVo.getUserAccount() != null && !("".equals(backOrderVo.getUserAccount()))) {
			UserInfo userInfo = new UserInfo();
			if (PatternUtils.isMobile(backOrderVo.getUserAccount())) {
				userInfo.setPhone(backOrderVo.getUserAccount());
			} else if (PatternUtils.isEmail(backOrderVo.getUserAccount())) {
				userInfo.setEmail(backOrderVo.getUserAccount());
			} else {
				userInfo.setUsername(backOrderVo.getUserAccount());
			}
			userInfo = userInfoService.selectUserInfoByParam(userInfo);
			if (userInfo != null) {
				backOrderVo.setUid(userInfo.getId());
			}
		}
		int totalCount = backOrderService.selectCountOrderByParam(backOrderVo);
		pageHelper pageHelper = new pageHelper(pageIndex, totalCount);
		List<Order> orders = backOrderService.selectCountOrderByParamForPage(backOrderVo, pageHelper.getStartIndex(),
				pageHelper.getPageNum());
		List<BackOrderVo> ordersVo = new ArrayList<>();
		for (Order order : orders) {
			BackOrderVo orderVo = new BackOrderVo();
			UserInfo userInfo = new UserInfo();
			userInfo.setId(order.getUid());
			userInfo = userInfoService.selectUserInfoByParam(userInfo);
			orderVo.setOrderId(order.getId());
			orderVo.setMid(order.getMid());
			orderVo.setOrderTime(order.getOrderTime());
			orderVo.setAddress(order.getDeliveryAddress());
			orderVo.setStatus(order.getStatus());
			orderVo.setTotalAmount(order.getTotalAmount());
			if (userInfo.getPhone() != null) {
				orderVo.setUserAccount(userInfo.getPhone());
			} else if (userInfo.getEmail() != null) {
				orderVo.setUserAccount(userInfo.getEmail());
			} else {
				orderVo.setUserAccount(userInfo.getUsername());
			}
			ordersVo.add(orderVo);
		}
		modelMap.addAttribute("ordersVo", ordersVo);
		modelMap.addAttribute("pageHelper", pageHelper);
		return modelMap;
	}

	/**
	 * 后台获取订单详情 *
	 * 
	 * @param orderId
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/getOrderInfo.shtml", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView getOrdersInfo(Integer pageIndex, Long orderId, ModelMap modelMap) {
		try {
			if (pageIndex == null) {
				pageIndex = 1;
			}
			int totalCount = backOrderService.selectCountByOrderId(orderId);
			pageHelper pageHelper = new pageHelper(pageIndex, totalCount);
			List<OrderInfo> orderInfos = backOrderService.selectCountByOrderIdForPage(orderId,
					pageHelper.getStartIndex(), pageHelper.getPageNum());
			List<BackOrderInfoVo> backOrdersInfoVo = new ArrayList<>();
			for (OrderInfo orderInfo : orderInfos) {
				BackOrderInfoVo backOrderInfoVo = new BackOrderInfoVo();
				backOrderInfoVo.setId(orderInfo.getId());
				backOrderInfoVo.setOrderId(orderInfo.getOrderId());
				backOrderInfoVo.setGoodName(goodsService.selectGoodsById(orderInfo.getGoodId()).getGoodsName());
				backOrderInfoVo.setBuyNum(orderInfo.getBuyNum());
				backOrderInfoVo.setSinPrice(orderInfo.getSinPrice());
				backOrdersInfoVo.add(backOrderInfoVo);
			}
			modelMap.addAttribute("ordersInfo", backOrdersInfoVo);
			modelMap.addAttribute("pageHelper", pageHelper);
			ModelAndView modelAndView = new ModelAndView("ordersInfo", modelMap);
			return modelAndView;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("后台订单详情获取失败：" + e.getMessage());
		}
		return null;
	}

	/**
	 * 商家修改订单的状态、收货地址、总金额
	 * 
	 * @param order
	 * @return
	 */
	@RequestMapping(value = "/updateOrder.shtml", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView updateOrder(HttpSession session, Order order) {

		try {
			Long orderId = (Long) session.getAttribute("orderId");
			if (orderId == null) {
				return new ModelAndView("redirect:/backOrder/userGetOrders.shtml");
			}
			order.setId(orderId);
			int code = backOrderService.updateOrder(order);
			if (code != 1) {
				return new ModelAndView("redirect:/backOrder/userGetOrders.shtml");
			}

			return new ModelAndView("redirect:/backOrder/userGetOrders.shtml");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("订单修改失败：" + e.getMessage());
			return new ModelAndView("userOrders", "msg", "订单更新出现异常，请重新操作");
		}
	}

	/**
	 * 进入更新订单页面
	 * 
	 * @return
	 */
	@RequestMapping("/toUpdateOrder.shtml")
	public ModelAndView toUpdateOrder(HttpSession session, Long orderId) {
		try {
			if (orderId == null) {
				return new ModelAndView("userOrders", "msg", "订单不存在");
			}

			Order order = backOrderService.selectOrderByOrderId(orderId);
			if (order == null) {
				return new ModelAndView("userOrders", "msg", "订单不存在");
			}
			session.setAttribute("orderId", orderId);
			return new ModelAndView("updateOrder", "order", order);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("订单修改失败：" + e.getMessage());
			return new ModelAndView("userOrders", "msg", "订单更新出现异常，请重新操作");
		}
	}

	
/**
 * 
 * @return 导出订单
 */
	
	 @RequestMapping(value ="/exportOrders.shtml")  
	    public ModelAndView exportOrders(HttpSession session,HttpServletRequest request,HttpServletResponse response){  
	        try {  
        	
	        	BackUser result=SecurityUtil.getBackUser();
				List<Order> orders=backOrderService.selectOrders(result.getId());
	            // 查出用户数据  
	            String title ="订单信息表";  
	            String[] rowsName=new String[]{"序号","订单号","地址","用户账号","总金额","订单状态","下单时间"};  
	            List<Object[]>  dataList = new ArrayList<Object[]>();  
	            Object[] objs = null;  
	            for (int i = 0; i < orders.size(); i++) {  
	            	Order order =orders.get(i);  
	                objs = new Object[rowsName.length]; 
	                objs[0]=i;
	                objs[1]= order.getId();  
	                objs[2]= order.getDeliveryAddress(); 
	                objs[3] = order.getUid();
	                objs[4] = order.getTotalAmount();
	                objs[5] = order.getStatus();
	                objs[6] = order.getOrderTime();
	                dataList.add(objs);  
	            }  
	            //   
	            ExportExcelUtils ex =new ExportExcelUtils(title, rowsName, dataList,response,request);  
	            ex.exportData();  
	              
	              
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	          
	        return null;  
	    }   

	
	

}
